package com.wlcb.jpower.chat.message.handler;

import com.wlcb.jpower.chat.entity.file.TbChatFile;
import com.wlcb.jpower.chat.reply.ReplyContext;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.chat.service.file.ChatFileService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.utils.WxMpInstance;
import it.sauronsoftware.jave.AudioUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;

/**
 * 普通消息接收
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    private ChatFileService chatFileService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String appId = context.get("appId").toString();
        try {
            //该handler 不处理事件类型的消息
            if ("event".equals(wxMessage.getMsgType())) {
                return null;
            }
            DataPacket dataPacket = toDataPacket(wxMessage, appId);
            ReplyContext replyContext = ReplyContext.getInstance(dataPacket, wxMessage, ImChatRecordCache.getInstance(wxMessage.getFromUser()));
            ReplyEntity replyEntity = replyContext.reply();
            if (Fc.notNull(replyEntity)) {
                //非人工回复
                replyEntity.sendReply();
            } else {
                //消息转发客服
                replyContext.forwardKefu();
            }
        } catch (WxErrorException e) {
            logger.error("WxErrorException：{}", e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("Exception：{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    //消息包
    private DataPacket toDataPacket(WxMpXmlMessage wxMessage, String appId) {
        DataPacket dataPacket = new DataPacket();
        dataPacket.setAction(ChatConstant.ChatActionEnum.CUSTOMER_USER_MESSAGE.type);
        dataPacket.setSendId(wxMessage.getFromUser());
        dataPacket.setReceiveType(ChatConfigConstant.UserType.CUSTOMER);
        dataPacket.setSendType(ChatConfigConstant.UserType.OTHER);
        dataPacket.setDate(System.currentTimeMillis());
        dataPacket.setAppId(appId);
        try {
            if (ChatConstant.MessageTypeEnum.TEXT.type.equals(wxMessage.getMsgType())) {
                dataPacket.setContent(wxMessage.getContent());
                dataPacket.setType(ChatConstant.MessageTypeEnum.TEXT.type);
            } else if (ChatConstant.MessageTypeEnum.IMAGE.type.equals(wxMessage.getMsgType())) {
                dataPacket.setType(ChatConstant.MessageTypeEnum.IMAGE.type);
                //图片消息  获取素材保存
                File file = WxMpInstance.getWxMp().switchoverTo(appId).getMaterialService().mediaDownload(wxMessage.getMediaId());
                TbChatFile chatFile = new TbChatFile();
                chatFile.setFilePath(file.getPath());
                chatFile.setFileRealName(file.getName());
                chatFileService.save(chatFile);
                dataPacket.setContent(chatFile.getId());
            } else if (ChatConstant.MessageTypeEnum.VOICE.type.equals(wxMessage.getMsgType())) {
                dataPacket.setType(ChatConstant.MessageTypeEnum.VOICE.type);
                //语言消息  获取素材保存
                File file = WxMpInstance.getWxMp().switchoverTo(appId).getMaterialService().mediaDownload(wxMessage.getMediaId());
                String[] name = file.getName().split("\\.");

                String path = WxMpInstance.getWxMp().getWxMpConfigStorage().getTmpDirFile().getPath() + File.separator + name[0] + ".mp3";
                AudioUtils.amrToMp3(file, new File(path));
                TbChatFile chatFile = new TbChatFile();
                chatFile.setFilePath(path);
                chatFile.setFileRealName(file.getName());
                chatFileService.save(chatFile);
                dataPacket.setContent(chatFile.getId());
                file.delete();
            } else if (ChatConstant.MessageTypeEnum.VIDEO.type.equals(wxMessage.getMsgType())) {
                dataPacket.setType(ChatConstant.MessageTypeEnum.VIDEO.type);
                //视频消息  获取素材保存
                File file = WxMpInstance.getWxMp().switchoverTo(appId).getMaterialService().mediaDownload(wxMessage.getMediaId());
                TbChatFile chatFile = new TbChatFile();
                chatFile.setFilePath(file.getPath());
                chatFile.setFileRealName(file.getName());
                chatFileService.save(chatFile);
                dataPacket.setContent(chatFile.getId());
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return dataPacket;
    }
}
